package com.gm.wholesale.bluetooth;
import android.Manifest;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.text.TextUtils;
import androidx.core.app.ActivityCompat;
import com.gm.commonlib.util.permission.PermissionUtil;
import com.gm.commonlib.util.permission.interfaces.IPermissionCallback;
import com.gm.commonlib.views.dialog.CustomDialog;
import com.gm.commonlib.views.dialog.loadingDialog.LoadingDialog;
import com.gm.commonlib.views.popupwindow.Popupwindow;
import com.gm.commonlib.views.toast.ToastUtil;
import com.gm.wholesale.bluetooth.bean.DeviceBean;
import com.gm.wholesale.bluetooth.interfaces.OnGetDeviceListener;
import com.gm.wholesale.bluetooth.service.BluetoothService;
import com.gm.wholesale.bluetooth.view.BlueDeviceListView;
import com.gm.wholesale.bluetooth.weightBlue.KHWeightBluetooth;
import com.gm.wholesale.bluetooth.weightBlue.WXLWeightBluetooth;
import com.gm.wholesale.util.HexUtil;
import com.youth.banner.util.LogUtils;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class BluetoothUtil {
    private BluetoothUtil() {
    }

    private static BluetoothUtil mBluetoothUtil;

    public static BluetoothUtil newInstance() {
        if (mBluetoothUtil == null) {
            mBluetoothUtil = new BluetoothUtil();
        }
        return mBluetoothUtil;
    }

    private BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

    public static void showNotPermiss(){
        ToastUtil.showToast("请在设置打开蓝牙权限和定位权限");

    }

    public boolean isConnection(BluetoothService bluetoothService) {
        if (bluetoothService == null) {
            return false;
        }
        if (bluetoothService.getState() == BluetoothService.STATE_CONNECTED) {
            return true;
        }
        return false;
    }


    public String getConnectionDevice(BluetoothService bluetoothService) {
        if (bluetoothService != null && bluetoothService.mdevice != null) {
            return bluetoothService.mdevice.getAddress();
        }
        return "";
    }

    public DeviceBean getConnectionDevice(Context context, BluetoothService bluetoothService) {
        if (context == null) return null;
        DeviceBean deviceBean = new DeviceBean();
        if (bluetoothService != null && bluetoothService.mdevice != null) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                if (ActivityCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
                    return null;
                }
            }
            deviceBean.setName(bluetoothService.mdevice.getName());
            deviceBean.setAddress(bluetoothService.mdevice.getAddress());
        }
        return deviceBean;
    }


    public synchronized void cancelDiscovery(Context context) {
        if (mBluetoothAdapter != null) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                if (ActivityCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_SCAN) == PackageManager.PERMISSION_GRANTED) {
                    mBluetoothAdapter.cancelDiscovery();
                }
            } else {
                mBluetoothAdapter.cancelDiscovery();
            }
        }

    }


    /**
     * 获取BluetoothAdapter对象，并判断蓝牙是否获取到
     */
    public boolean isBlueToothCanUse() {
        //获取BluetoothAdapter对象
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
            return false;
        }

        return true;
    }


    public void connectDevice(Context context, String device, BluetoothService bluetoothService) {
        LoadingDialog.newLoadingDialog().show(context);
        if (bluetoothService == null) {
            ToastUtil.showToast("mBlueService is null");
            LoadingDialog.newLoadingDialog().hid();
            return;
        }
        if (device!=null && device.length() > 0 && mBluetoothAdapter != null) {
            BluetoothDevice bluetoothDevice = mBluetoothAdapter.getRemoteDevice(device);
            if (device != null && bluetoothDevice != null) {
                bluetoothService.stop();
                bluetoothService.connect(bluetoothDevice);
            }
        }
    }

    public static String getConnectionWeightDevice(Context context){
        KHWeightBluetooth khWeightBluetooth=    KHWeightBluetooth.getBluetoothManger(context);
        WXLWeightBluetooth wxlWeightBluetooth=WXLWeightBluetooth.getBluetoothManger(context);

        if (wxlWeightBluetooth.getConnectionDeviceAd(context)!=null){
            return wxlWeightBluetooth.getConnectionDeviceAd(context);
        }
        if (khWeightBluetooth.getConnectionDeviceAd(context)!=null){
            return khWeightBluetooth.getConnectionDeviceAd(context);
        }
        return "";

    }


    /**
     * 获取已配对的蓝牙设备
     */
    public Set<DeviceBean> getConnectDevices(Context context, String filter) {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
                showNotPermission();
                return null;
            }
        }
        if (mBluetoothAdapter == null) {
            return null;
        }
        //打印出已配对的设备
        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
        if (pairedDevices.size() > 0) {
            Set<DeviceBean> deviceBeans = new HashSet<>();
            for (BluetoothDevice device : pairedDevices) {
                if (device != null && device.getAddress() != null) {


                    if (device.getName().startsWith(filter)) {
                        DeviceBean deviceBean = new DeviceBean();
                        deviceBean.setName(device.getName());
                        deviceBean.setAddress(device.getAddress());
                        deviceBean.setState(1);
                        deviceBeans.add(deviceBean);
                        return deviceBeans;
                    }


                }
            }
        } else {
            return null;
        }
        return null;

    }


    // todo 查找设备
    public synchronized void startFindDevice(Context context, BroadcastReceiver mReceiver) {
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        filter.addAction(BluetoothDevice.ACTION_FOUND);
        filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
        filter.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
        filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        context.registerReceiver(mReceiver, filter);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_SCAN) == PackageManager.PERMISSION_GRANTED) {
                if (mBluetoothAdapter!=null){
                    mBluetoothAdapter.startDiscovery();
                }
            }
        } else {
            if (mBluetoothAdapter!=null){
                mBluetoothAdapter.startDiscovery();
            }

        }


    }

    public void showBluDevices(Activity activity, List<String> filter, OnGetDeviceListener listener) {
        BlueDeviceListView blueDeviceListView = new BlueDeviceListView(activity);

        blueDeviceListView.setOnBlueDeviceChoiceListener(device -> {
            Popupwindow.hiddenPop();
            if (listener != null) {
                listener.onGetDevice(device);
            }

        });
        blueDeviceListView.startFindDevice(filter);
        Popupwindow.showPopCenterView(activity, blueDeviceListView);
    }


    public void showBluDevices(Activity activity, String filter, OnGetDeviceListener listener) {
        List<String> filters=new ArrayList<>();
        filters.add(filter);
        showBluDevices(activity,filters,listener);
    }


    public void showNotPermission() {
        LoadingDialog.newLoadingDialog().hid();
        ToastUtil.showToast("没有蓝牙或者定位权限，请在设置开启");
    }


    public void setFailState(BluetoothService bluetoothService) {
        if (bluetoothService != null) {
            bluetoothService.setState(BluetoothService.STATE_NONE);
        }
    }


    public synchronized void print(String data, BluetoothService bluetoothService) {
        LogUtils.d("printprint: " + data);
        if (!TextUtils.isEmpty(data) && bluetoothService != null) {
            bluetoothService.write(HexUtil.hexString2Bytes(data));
        }
    }

    public void startConnectWeightBlue(Activity context, OnGetDeviceListener listener) {
        CustomDialog customDialog = new CustomDialog(context);
        customDialog.setMessage("蓝牙秤未连接是否连接?");
        customDialog.setLeftText("取消");
        customDialog.setTitle("提示");
        customDialog.setRightText("确定");
        customDialog.setOnRightListener(new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                if (!isBlueToothCanUse()) {
                    ToastUtil.showToast("蓝牙未开启，请先打开蓝牙");
                    return;
                }
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                    PermissionUtil.aplyBluePermission(context, new IPermissionCallback() {
                        @Override
                        public void onPermissionResult(boolean result, Set<String> dataSet) {
                            if (result) {
                               showBluDevices(context,WeightBlueType.getWeightFilter(),listener);
                            } else {
                                ToastUtil.showToast("扫描设备失败，请在手机设置打开定位和蓝牙权限");
                            }
                        }
                    });
                } else {
                    showBluDevices(context,WeightBlueType.getWeightFilter(),listener);
                }


            }
        });
        customDialog.show();


    }

    public static void setDevice(Context context,BluetoothDevice device,DeviceBean deviceBean){
        if (context==null || device==null || deviceBean==null){
            return;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED) {
                deviceBean.setName(device.getName());
            }
        }
        else {
            deviceBean.setName(device.getName());
        }
        deviceBean.setAddress(device.getAddress());
    }

    public void destroy() {
        mBluetoothUtil=null;
        mBluetoothAdapter=null;
    }




}
